import { defineStore } from "pinia"; 
import { userLoginAPI , getUserInfoAPI } from '@/api/user'
import { SET_TOKEN , GET_TOKEN , REMOVE_TOKEN } from '@/utils/SET_TKOEN'
import router from "@/router";
const useUserStore = defineStore('userStore',{
    state:()=>{
        return {
            userInfo:GET_TOKEN('user')?GET_TOKEN('user'):'',
            token:GET_TOKEN('token')?GET_TOKEN('token'):'',
        }
    },
    actions:{
        // 登录
        async login(userInfo){
           let result = await userLoginAPI(userInfo) 
           this.token = result.data.token
           this.userInfo = result.data.user
           SET_TOKEN('token',this.token)
           SET_TOKEN('user',JSON.stringify(this.userInfo))
        },
        // 退出登录
        logout(){
            this.token = ''
            this.userInfo = ''
            REMOVE_TOKEN('token')
            REMOVE_TOKEN('user')
            router.push('/')
        },
        //获取用户详情
        async getUserInfo() {
           if(!this.token) {
            return
           }
            if(this.userInfo?._id) {
                let result = await getUserInfoAPI(this.userInfo._id)
                console.log(result);
                this.userInfo = result.data
                SET_TOKEN('user',JSON.stringify(this.userInfo))
            }
        }
    },
    getters:{
        
    }
})

export default useUserStore